﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfAppTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
        }

        private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            var samples = await this.LoadSamples();
            this.Samples = samples;
        }


        public Dictionary<Type, string> Samples
        {
            get { return (Dictionary<Type, string>)GetValue(SamplesProperty); }
            set { SetValue(SamplesProperty, value); }
        }

        public static readonly DependencyProperty SamplesProperty =
            DependencyProperty.Register("Samples", typeof(Dictionary<Type, string>), typeof(MainWindow), new PropertyMetadata(null));



        /// <summary>
        /// 加载程序集中定义的示例
        /// </summary>
        /// <returns></returns>
        private async Task<Dictionary<Type, string>> LoadSamples()
        {
            var asses = AppDomain.CurrentDomain.GetAssemblies();
            var pt = typeof(Page);
            var st = typeof(ISample);
            Dictionary<Type, string> list = new Dictionary<Type, string>();
            await Task.Run(delegate
            {
                foreach (var ass in asses)
                {
                    var etypes = ass.GetExportedTypes();
                    foreach (var type in etypes)
                    {
                        if (pt.IsAssignableFrom(type) && st.IsAssignableFrom(type))
                        {
                            var sna = type.GetCustomAttribute<SampleNameAttribute>();

                            list.Add(type, sna == null ? type.Name : sna.Name);
                        }
                    }
                }
            });
            return list;
        }

        private void menu_Checked(object sender, RoutedEventArgs e)
        {
            if (e.OriginalSource is ToggleButton toggleButton)
            {
                if (toggleButton.Tag is Type t)
                {
                    var ins = Activator.CreateInstance(t);
                    this.frame.Navigate(ins);
                }
            }
        }
    }
}
